<?php

namespace Trawind\Helpers;

use Illuminate\Redis\RedisManager;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Swoole\Coroutine;
use Swoole\Exception;
use Trawind\Basics\Enums\ServiceDomain;
use Illuminate\Support\Facades\Request;
use Trawind\VerifyPermission\VerifyPermission;

/**
 * Class UserHelper
 *
 * @package Trawind\Helpers
 */
class UserHelper
{

    /**
     * @return mixed
     */
    public static function userInfo()
    {
        //        return json_decode(Request()->header('user-info'), true);

        $verifyPermission = new VerifyPermission();
        $user = $verifyPermission->user();
        return $user['data'] ?? [];
    }

    /**
     * @param  string|null  $default
     * @return mixed|string|null
     */
    public static function tenantId(?string $default = null)
    {
        if (SystemHelper::runningInConsole()) {
            return config('app.tenant_id');
        }
        $hostname = Request::getHost();
        $tenantId = explode('.', $hostname)[0];
        $tenantId = tenant('tenant_id') ?? $tenantId;

        if ($tenantId != "develop" && $tenantId != "system") {
            return $tenantId ?? $default;
        }
        return $default;
    }

    public static function setConsoleTenantId(string $tenant_id)
    {
        return config(['app.tenant_id' => $tenant_id]);
    }

    /**
     * @param  string|null  $default
     * @return mixed|string|null
     */
    public static function roleId(?string $default = null)
    {
        return self::userInfo()['last_signin_role_id'] ?? $default;
    }

    /**
     * @param  string|null  $default
     * @return mixed|string|null
     */
    public static function userId(?string $default = null)
    {
        return self::userInfo()['id'] ?? $default;
    }

    /**
     * @param  string|null  $default
     * @return mixed|string|null
     */
    public static function employeeId(?string $default = null)
    {
        $userInfo = self::userInfo();
        if ($userInfo['person_type_id'] == 10) {
            return $userInfo['person_id'];
        }
        return $default;
    }


    public static function token()
    {
        if (SystemHelper::runningInConsole()) {
            $tokenKey = 'console:token';
            $redis = SystemHelper::redis();
            if (is_null($token = $redis->get($tokenKey))) {
                $result = HttpClientHelper::guzzle([
                    'base_uri' => ServiceDomain::USER_DOMAIN(false),
                    'verify' => false,
                    'headers' => [
                        'Accept' => 'application/json',
                    ]
                ])
                    ->post('/oauth/token', [
                        'form_params' => [
                            "grant_type" => "password",
                            "client_id" => 4,
                            "client_secret" => "4rI3aB2cfNhfLWv4EbVwxeI84uqHcHaF0wL5fZts",
                            "scope" => "console",
                            "username" => "console@yeamart.com",
                            "password" => "xPitmu0qmgvQ",
                        ]
                    ])
                    ->getBody()
                    ->getContents();

                $result = json_decode($result, true);
                $redis->setex($tokenKey, $result['expires_in'],
                    $token = "{$result['token_type']} {$result['access_token']}");
            }
            return $token;
        }

        return request()->header('Authorization');
    }

}
